<template>
  <!-- 我的 -->
  <view class="container">
    <image class="contain_bg" src="https://tcjyh2022.oss-cn-hangzhou.aliyuncs.com/nywx/mine_bg.png" mode=""></image>
    <view class="contain_body" :style="{ top: CustomBar + 'px' }">
      <!-- 待写 未登录 -->
      <view v-if="isAuth" class="contain_top">
        <img style="width: 130rpx; height: 130rpx; border-radius: 50%" :src="userInfo.avatar" alt=""
          @tap="uploadFile" />
        <view class="top_name">
          <view class="top_name-txt"><text>{{ userInfo.nickname || userInfo.username }}</text>
          <text style="font-size: 24rpx;" v-if="userInfo.water_name">{{ userInfo.water_name || '' }}</text>
          <text style="font-size: 24rpx;" >ID： {{ userInfo.my_invite_code || '' }}</text>
          <view style="font-size: 24rpx;display:flex" >{{ returnName(userInfo.gas_name) }} <image style="width: 30rpx;height: 30rpx;" v-for="item in star_num" :key="item" src="../../static/star.svg"></view>
        </view>
          <view class="top_name-btn" v-if="userInfo.balance && userInfo.balance > 0" @tap="goWithdraw">去提现</view>
        </view>
      </view>
        <view v-else class="contain_top" @tap="goLogin">
          <img style="width: 130rpx; height: 130rpx" src="https://mp-7bd569d5-2369-48a6-b477-e8c6b6ccf6ce.cdn.bspapp.com/10011693836581_.pic.jpg" alt="" />
          <text class="top_name">立即登录</text>
        </view>
      <view class="contain_third">
        <view class="third_item">
          <view class="third_item_top">
            {{ userInfo.water_amount_back || 0 }}
          </view>
          <view class="third_item_bottom">
            <text>剩余积分</text>
            
          </view>
        </view>
        <view class="third_item" @tap="goJifen(1)">
          <view class="third_item_top">
            {{ userInfo.balance ? userInfo.balance : 0 }}
          </view>
          <view class="third_item_bottom">
            <text>我的积分</text>
            <image class="arrow_right_arrow" src="https://tcjyh2022.oss-cn-hangzhou.aliyuncs.com/nywx/mine_right2.svg"
              mode="">
            </image>
          </view>
        </view>
        
        <view class="third_item" @tap="goContract(1)">
          <view class="third_item_top">
            {{ contract_num.car || 0 }}
          </view>
          <view class="third_item_bottom">
            <text>我的券包</text>
            <image class="arrow_right_arrow" src="https://tcjyh2022.oss-cn-hangzhou.aliyuncs.com/nywx/mine_right2.svg"
              mode="">
            </image>
          </view>
        </view>
      </view>
      <view class="contain_third">
        <view class="third_item">
          <view class="third_item_top">
            {{ userInfo.gas_amount_back ? userInfo.gas_amount_back : 0 }}
          </view>
          <view class="third_item_bottom">
            <text>剩余油卡</text>
            
          </view>
        </view>
        <view class="third_item" @tap="goJifen(6)">
          <view class="third_item_top">
            {{ userInfo.gas_amount_remind ? userInfo.gas_amount_remind : 0 }}
          </view>
          <view class="third_item_bottom">
            <text>待释放油卡</text>
            <image class="arrow_right_arrow" src="https://tcjyh2022.oss-cn-hangzhou.aliyuncs.com/nywx/mine_right2.svg"
              mode="">
            </image>
          </view>
        </view>
        
        <view class="third_item" @tap="goContract(2)">
          <view class="third_item_top">
            {{ contract_num.gas || 0 }}
          </view>
          <view class="third_item_bottom">
            <text>我的加油包</text>
            <image class="arrow_right_arrow" src="https://tcjyh2022.oss-cn-hangzhou.aliyuncs.com/nywx/mine_right2.svg"
              mode="">
            </image>
          </view>
        </view>
      </view>

      <view class="contain_public contain_second">
        <view v-if="userInfo._id && userInfo.role && userInfo.role[0]=='admin'" class="second_item" @tap="goStatistic()">
          <view class="second_item_l">
            <image class="second_item_img" src="../../static/yaoqing.svg" mode=""></image>
            <text>数据分析</text>
          </view>
          <view class="second_item_r">
            <image class="second_item_arrow" src="https://tcjyh2022.oss-cn-hangzhou.aliyuncs.com/nywx/mine_right3.svg"
              mode=""></image>
          </view>
        </view>
        <view class="second_item" v-for="(item, index) in secondTabs" :key="index" @tap="goOtherUrl(item)">
          <view class="second_item_l">
            <image class="second_item_img" :src="item.img" mode=""></image>
            <text>{{ item.title }}</text>
          </view>
          <view class="second_item_r">
            <text v-if="item.id==1 && unReadArr.length > 0" class="second_item_r_num">{{
              unReadArr.length
            }}</text>
            <image class="second_item_arrow" src="https://tcjyh2022.oss-cn-hangzhou.aliyuncs.com/nywx/mine_right3.svg"
              mode=""></image>
          </view>
        </view>
      </view>
      
      <view v-if="userInfo._id" class="invite-btn" @tap="logout">
        切换账号
      </view>
    </view>
    <uni-popup ref="popup" type="top">
      <user-login :encryptedKey="encryptedKey" :inviteCode="inviteCode"></user-login>
    </uni-popup>
  </view>
</template>

<script>
  import userLogin from '../../components/userlogin/userlogin.vue'
  export default {
    data() {
      return {
        isAuth: false,
        contract_num: {
          car: 0,
          gas:0
        },
        CustomBar: this.CustomBar,
        userInfo: {}, //商户信息
        inviteCode: '',
        secondTabs: [
          {
          	id: 2,
          	img: '../../static/yaoqing.svg',
          	title: '停车券包邀请',
          	url: '/pages/myuser/myuser'
          },
          {
          	id: 2,
          	img: '../../static/yaoqing.svg',
          	title: '加油卡邀请',
          	url: '/pages/mygas/mygas'
          },
          // {
          // 	id: 5,
          // 	img: '../../static/xiaoxi.svg',
          // 	title: '我的签约',
          // 	url: '/pages/mysign/mysign'
          // },
          {
          	id: 5,
          	img: '../../static/xiaoxi.svg',
          	title: '我的资料',
          	url: '/pages/myinfo/myinfo'
          },
          {
            id: 1,
            img: '../../static/xiaoxi.svg',
            title: '我的消息',
            url: '/pages/notice/notice'
          },
          {
            id: 3,
            img: '../../static/fankui.svg',
            title: '反馈建议',
            url: '/pages/feedback/feedback'
          },
          {
            id: 4,
            img: '../../static/xieyi.svg',
            title: '相关说明',
            url: '/pages/info/info'
          }
        ],
        encryptedKey: '',
        star_num: 0,
        unReadArr: [] // 未读消息
      }
    },
    components: {
      userLogin
    },
    async onShareAppMessage(options) {
      if (options.from === "menu") {
        console.log(1111);
      }
      return {
        title: "城市车位：您的车位选择",
        path: "/pages/index/index",
        imageUrl: "https://mp-7bd569d5-2369-48a6-b477-e8c6b6ccf6ce.cdn.bspapp.com/2023/09/01/zhihuitingche.png",
      };
    },
    onPullDownRefresh() {
      this.isAuth = vk.checkToken()
      if (this.isAuth) {
        vk.userCenter.getCurrentUserInfo({
          success: (data) => {
            // 成功后的逻辑
            vk.setVuex('$user.userInfo', data.userInfo)
            this.userInfo = data.userInfo
            this.getContractNum()
          }
        });
      }
      setTimeout(function() {
        uni.stopPullDownRefresh();
      }, 1000);
    },
    onLoad() {
      uni.$on('loginSuccess', () => {
        vk.userCenter.getCurrentUserInfo({
          success: (data) => {
            // 成功后的逻辑
            vk.setVuex('$user.userInfo', data.userInfo)
            this.userInfo = data.userInfo
            console.log(this.userInfo, 'this.userInfo---')
            this.getContractNum()
            this.$refs.popup.close()
            this.isAuth = vk.checkToken()
            this.getNoticeList()
          }
        });
      })
    },
    onUnload() {
      uni.$off('loginSuccess')
    },
    onShow() {
      this.isAuth = vk.checkToken()
      if (this.isAuth) {
        vk.userCenter.getCurrentUserInfo({
          success: (data) => {
            // 成功后的逻辑
            vk.setVuex('$user.userInfo', data.userInfo)
            this.userInfo = data.userInfo
            this.getContractNum()
            this.getNoticeList()
          }
        });
      }
      // #ifdef MP
      this.getKey()
      // #endif
    },
    methods: {
      returnName(name) {
        if (!name) {
          return ''
        }
        if (name.indexOf('一星') > -1) {
          this.star_num = 1
          return 'VIP'
        }
        if (name.indexOf('二星') > -1) {
          this.star_num = 2
          return 'VIP'
        }
        
        return name
      },
      logout() {
        vk.callFunction({
          url: 'user/pub/logout',
          title: '退出中...',
          success: (res) => {
            this.userInfo = {}
            this.unReadArr = []
            this.contract_num = 0
            this.isAuth = false
          }
        })
      },
      getNoticeList() {
        this.unReadArr = []
        vk.callFunction({
          url: 'user/kh/messageList',
          title: '加载中...',
          data: {
            user_id: this.userInfo._id,
          },
          success: (res) => {
            if(res.rows.length> 0) {
              res.rows.map(item => {
                if (item.status == 1) {
                  this.unReadArr.push(item)
                }
              })
            }
          
          }
        })
      },
      getKey() {
        let that = this;
        vk.userCenter.code2SessionWeixin({
          data: {
            needCache: true
          },
          success: (data) => {
            that.encryptedKey = data.encryptedKey;
          },
        });
      },
      goLogin() {
        // #ifdef MP
          if (!this.isAuth) {
            this.inviteCode = uni.getStorageSync('invite_code')
            this.$refs.popup.open()
          }
        // #endif
        // #ifdef H5
        uni.navigateTo({
          url: '/pages/login/login'
        })
        // #endif
      },
      goStatistic() {
        uni.navigateTo({
          url: '/pages/statistic/statistic'
        })
      },
      goWithdraw() {
        uni.navigateTo({
          url: '/pages/withdraw/withdraw'
        })
      },
      goJifen(type) {
        if (!this.isAuth) {
          this.goLogin()
        } else {
          uni.navigateTo({
            url: '/pages/jifen/jifen?type=' + type
          })
        }
      },
      goContract(type) {
        if (!this.isAuth) {
          this.goLogin()
        } else {
          uni.navigateTo({
            url: '/pages/contract/contract?type=' + type
          })
        }
      },
      goOtherUrl(item) {
        if (item.id == 1 || item.id == 2 || item.id == 3) {
          if (!this.isAuth) {
            this.goLogin()
            return
          }
        }
        uni.navigateTo({
          url: item.url
        })
      },
      getContractNum() {
        // 获取我的券包合同数量
       this.contract_num = {
         car: 0,
         gas: 0
       }
        vk.callFunction({
          url: 'user/kh/contractList',
           title: '加载中...',
          data: {
            user_id: this.userInfo._id
          },
          success: (res) => {
            // this.contract_num = res.total
            if(res.rows.length > 0) {
              for(let i = 0; i < res.rows.length;i++) {
                if (res.rows[i].type == 1) {
                  this.contract_num.car++
                }
                if (res.rows[i].type == 2) {
                  this.contract_num.gas++
                }
              }
            }
   
          }
        })
      },
      getNotice() {},
      uploadFile() {
        
        
        
        let that = this
        uni.chooseImage({
          count: 1,
          success(res) {
            console.log(res);
            if (res.tempFilePaths.length > 0) {
              let filePath = res.tempFilePaths[0]
        
              // callback方式，与promise方式二选一即可
              uniCloud.uploadFile({
                filePath: filePath,
                cloudPath:  new Date().getTime()+'.jpg',
                onUploadProgress: function(progressEvent) {
                  console.log(progressEvent);
                  var percentCompleted = Math.round(
                    (progressEvent.loaded * 100) / progressEvent.total
                  );
                },
                success(res) {
                  console.log(res, 'res----')
                  vk.callFunction({
                    url: 'user/kh/setAvatar',
                    data: {
                      avatar: res.fileID
                    },
                    success: (info) => {
                      that.userInfo.avatar = res.fileID
                    }
                  })
                },
                fail() {},
                complete() {}
              });
        
            }
          }
        });
      }
    }
  }
</script>

<style scoped lang="scss">
  .invite-btn {
    color: #fff;
    background-color: #005ECD;
    border-radius: 100rpx;
    width: 100%;
    height: 66rpx;
    text-align: center;
    line-height: 66rpx;
    font-family: PingFang SC;
    font-size: 32rpx;
    font-style: normal;
    font-weight: 600;
  }
  .container {
    position: relative;

    .contain_bg {
      width: 100%;
      height: 636rpx;
      // background: linear-gradient(180.56deg, #9C85FF 0.72%, rgba(125, 96, 251, 0) 99.76%);
    }

    .contain_body {
      position: absolute;
      left: 0;
      width: calc(100% - 60rpx);
      padding: 0 30rpx;

      .contain_top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 30rpx;

        .top_name {
          margin-left: 30rpx;
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;

          &-txt {
            font-size: 34rpx;
            font-weight: 600;
            display: flex;
            flex-direction: column;
          }

          &-btn {
            width: 176rpx;
            height: 68rpx;
            text-align: center;
            line-height: 68rpx;
            background: #005ecd;
            border-radius: 100rpx;
            color: #fff;
            font-family: PingFang SC;
            font-size: 24rpx;
            font-style: normal;
            font-weight: 400;
          }
        }
      }

      .contain_public {
        margin-bottom: 24rpx;
        padding: 20rpx 30rpx;
        border-radius: 18rpx;
        background-color: #fff;
      }

      .top_r_arrow {
        width: 34rpx;
        height: 34rpx;
      }

      .top_r_level_arrow {
        width: 26rpx;
        height: 26rpx;
      }

      .contain_third {
        margin-bottom: 24rpx;
        display: flex;
        justify-content: space-between;
        border-radius: 18rpx;
        padding: 24rpx;
        background-color: #fff;
        height: 114rpx;

        .third_item {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-direction: column;

          .third_item_top {
            display: flex;
            align-items: center;
            font-weight: 600;
            font-size: 40rpx;
            color: #005ecd;
          }

          .third_item_bottom {
            display: flex;
            align-items: center;
            margin-top: 23rpx;
            font-size: 24rpx;

            .arrow_right_arrow {
              width: 10rpx;
              height: 20rpx;
              margin-left: 8rpx;
            }
          }
        }
      }

      .contain_second {
        .second_item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 27rpx 0;
          font-size: 26rpx;

          .second_item_l {
            display: flex;
            align-items: center;

            .second_item_img {
              width: 30rpx;
              height: 30rpx;
              margin-right: 25rpx;
            }
          }

          .second_item_r {
            position: relative;
            display: flex;
            align-items: center;

            .second_item_arrow {
              width: 34rpx;
              height: 34rpx;
            }

            &_num {
              position: absolute;
              top: 50%;
              transform: translateY(-50%);
              right: 50rpx;
              width: 40rpx;
              height: 40rpx;
              border-radius: 50%;
              font-size: 18rpx;
              background: #005ecd;
              color: #fff;
              line-height: 40rpx;
              text-align: center;
            }
          }
        }
      }
    }
  }
</style>